﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace MetaSharp.Transformation
{
    public class ArrayList<T> : List<T>, IImmutableArray<T>
    {
        public ArrayList() { }
        public ArrayList(IEnumerable<T> items)
            : base(items)
        { }
        public ArrayList(params T[] items)
            : base(items)
        { }

        public int Length
        {
            get { return this.Count; }
        }

        public IImmutableArray<T> Concat(IImmutableArray<T> items)
        {
            return new Concatenated(this, items);
        }

        private class Concatenated : IImmutableArray<T>
        {
            private IImmutableArray<T> _left;
            private IImmutableArray<T> _right;
            public Concatenated(IImmutableArray<T> left, IImmutableArray<T> right)
            {
                _left = left;
                _right = right;
            }

            public T this[int x]
            {
                get
                {
                    if (x < _left.Length)
                        return _left[x];
                    else
                        return _right[x - _left.Length];
                }
            }

            public int Length
            {
                get
                {
                    return _left.Length + _right.Length;
                }
            }

            public IImmutableArray<T> Concat(IImmutableArray<T> items)
            {
                return new Concatenated(this, items);
            }

            public void CopyTo(int index, T[] array, int arrayIndex, int count)
            {
                // TODO: do I need this?
                throw new NotImplementedException();
            }

            public IEnumerator<T> GetEnumerator()
            {
                foreach (var left in _left)
                    yield return left;
                foreach (var right in _right)
                    yield return right;
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return this.GetEnumerator();
            }
        }
    }
}
